import { reactive, toRefs } from '@vue/composition-api'

export default function usePagination () {
  const pagination = reactive({
    data: {
      total: 0,
      per_page: 10,
      pages: 1,
      page: 1,
      has_prev: false,
      has_next: false,
      prev_num: 0,
      next_num: 0,
      items: [],
    },
    loading: false,
    layout: 'total, prev, pager, next, sizes, jumper',
    sizes: ['5', '10', '20', '50', '100'],
  })

  /**
   * currentPage 改变时会触发
   * @param {*} callback 回调函数
   * @param {*} val 参数
   */
  function handlePageChange (callback, args) {
    return new Promise((resolve, reject) => {
      callback(...args).then((data) => {
        pagination.data = data
        resolve(data)
      }).catch((error) => {
        reject(error)
      })
    })
  }

  /**
   * 更改分页参数
   * @param {*} [paging={}] pagination.data arg
   */
  function updatePaginationParams (paging = {}) {
    const keys = Object.keys(paging)
    const pag = pagination.data
    keys.forEach((key) => {
      if (pag[key] !== undefined) {
        pagination.data[key] = paging[key]
      }
    })
    return pag
  }

  /**
   * pageSize 改变时会触发
   * @param {*} callback  回调函数
   * @param {*} arg  参数
   */
  function handleSizeChange (callback, arg) {
    callback(...arg)
  }

  /**
   * 用户点击上一页按钮改变当前页后触发
   */
  function handlePrevClick () {
  }

  /**
   * 用户点击下一页按钮改变当前页后触发
   */
  function handleNextClick (callback, val) {
    return new Promise((resolve, reject) => {
      callback(...val).then((data) => {
        pagination.data = data
        resolve(data)
      }).catch((error) => {
        reject(error)
      })
    })
  }

  return {
    pagination,
    handlePageChange,
    handleSizeChange,
    handlePrevClick,
    handleNextClick,
    updatePaginationParams,
  }
}
